package com.glp.work.flow.controller;

import com.aliyuncs.utils.StringUtils;
import com.github.pagehelper.util.StringUtil;
import com.glp.common.reponse.BaseResult;
import com.glp.work.flow.config.mq.ExchangeQueueConfig;
import com.glp.work.flow.constant.APICode;
import com.glp.work.flow.constant.Constants;
import com.glp.work.flow.dto.ProcTaskInfoDTO;
import com.glp.work.flow.dto.request.AssignUserInfoDTO;
import com.glp.work.flow.dto.request.ProDefDTO;
import com.glp.work.flow.dto.request.ProcTaskAssignInfoDTO;
import com.glp.work.flow.exception.APIException;
import com.glp.work.flow.mapper.WfPlatformDefMapper;
import com.glp.work.flow.pojo.WfPlatformDef;
import com.glp.work.flow.request.RoleRequest;
import com.glp.work.flow.response.RolesResponse;
import com.glp.work.flow.service.client.PermissionClient;
import com.glp.work.flow.service.UserService;
import com.glp.work.flow.service.UserTaskAssignService;
import com.glp.work.flow.service.WfPlatformDefService;
import com.glp.work.flow.utils.TraceIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 任务分配
 *
 * @author pengjia
 * @version 2020年3月9日 上午11:53:35
 */
@RestController
@Slf4j
@RequestMapping("/wf/proc")
@Api(tags = "任务分配")
public class UserTaskAssignController {

    @Autowired
    public UserTaskAssignService userTaskAssignService;

    @Resource
    private PermissionClient permissionService;

    @Autowired
    private WfPlatformDefMapper wfPlatformDefMapper;

    @Autowired
    private WfPlatformDefService wfPlatformDefService;

    @Resource
    private UserService userService;

    @ApiOperation(value = "保存任务分配的信息", notes = "保存任务分配的信息")
    @PostMapping(value = "/task/assign/save", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BaseResult<String> saveProcTaskAssignInfo(@RequestBody ProcTaskAssignInfoDTO procTaskAssignInfoDTO) {
        log.info("保存任务分配的信息：{}", procTaskAssignInfoDTO);
        userTaskAssignService.saveTaskAssignInfo(procTaskAssignInfoDTO);
        return new BaseResult<>(APICode.SUCCESS.getCode(), "保存任务分配的信息成功！", "保存任务分配的信息成功！" + TraceIDUtils.getLogTraceId());
    }

    @ApiOperation(value = "查询所有的用户和角色信息", notes = "查询所有的用户和角色信息")
    @GetMapping(value = "/get/all/users")
    @ResponseBody
    public BaseResult<?> queryAllUserInfo(String type) {
        if (StringUtil.isNotEmpty(type)) {
            if (Constants.STATUS_1.equals(type)) {
                List<AssignUserInfoDTO> resultList = userTaskAssignService.queryAllUserInfo();
                log.info("查询所有的用户信息。{}", resultList);
                return new BaseResult<>(APICode.SUCCESS.getCode(), "查询所有的用户信息成功！" + TraceIDUtils.getLogTraceId(), resultList);
            } else if (Constants.STATUS_0.equals(type)) {
                RoleRequest roleRequest = new RoleRequest();
                List<WfPlatformDef> wfPlatformDefs = wfPlatformDefMapper.selectAll();
                ArrayList<String> appIds = new ArrayList<>();
                wfPlatformDefs.stream().forEach(wfPlatformDef ->
                        appIds.add(wfPlatformDef.getPlatformId())
                );
                roleRequest.setAppIds(appIds);
                List<RolesResponse> rolesResponses = userService.enabledRoles(roleRequest);
                for (WfPlatformDef wfPlatformDef : wfPlatformDefs) {
                    for (RolesResponse rolesResponse : rolesResponses) {
                        if (wfPlatformDef.getPlatformId().equals(rolesResponse.getAppId())) {
                            rolesResponse.setAppName(wfPlatformDef.getPlatformName());
                        }
                    }
                }
                log.info("查询所有可用角色信息。{}", rolesResponses);
                return new BaseResult<>(APICode.SUCCESS.getCode(), "查询所有的角色信息成功！" + TraceIDUtils.getLogTraceId(), rolesResponses);
            }
        } else {
            List<AssignUserInfoDTO> resultList = userTaskAssignService.queryAllUserInfo();
            log.info("查询所有的用户信息。{}", resultList);
            return new BaseResult<>(APICode.SUCCESS.getCode(), "查询所有的用户信息成功！" + TraceIDUtils.getLogTraceId(), resultList);
        }
        return null;
    }

    @ApiOperation(value = "查询所有流程及其下所有任务信息", notes = "查询所有流程及其下所有任务信息")
    @PostMapping(value = "/get/all/tasks", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BaseResult<List<ProcTaskInfoDTO>> queryProAllTaskDefInfo(@RequestBody ProDefDTO req) {
        List<ProcTaskInfoDTO> taskList = userTaskAssignService.queryProAllTaskDefInfo(req);
        log.info("查询所有流程及其下所有任务信息。{}", taskList);
        return new BaseResult<>(APICode.SUCCESS.getCode(), "查询所有流程及其下所有任务信息成功！" + TraceIDUtils.getLogTraceId(), taskList);
    }

    @ApiOperation(value = "查询所有流程及其下所有任务信息(version--2.0)", notes = "查询所有流程及其下所有任务信息")
    @PostMapping(value = "/get/all/tasksnew", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BaseResult<List<ProcTaskInfoDTO>> queryProAllTaskDefInfoNew(@RequestBody ProDefDTO req) {
        List<ProcTaskInfoDTO> taskList = userTaskAssignService.queryProAllTaskDefInfoNew(req);
        log.info("查询所有流程及其下所有任务信息。{}", taskList);
        return new BaseResult<>(APICode.SUCCESS.getCode(), "查询所有流程及其下所有任务信息成功！" + TraceIDUtils.getLogTraceId(), taskList);
    }

    @ApiOperation(value = "查询当前节点外的其他节点", notes = "查询当前节点外的其他节点")
    @PostMapping(value = "/get/present/tasks", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BaseResult<List<Map<String, String>>> queryPresentTaskDefInfo(@RequestBody ProDefDTO req) {
        List<Map<String, String>> taskList = userTaskAssignService.queryPresentTaskDefInfo(req);
        log.info("查询当前节点外的其他节点。{}", taskList);
        return new BaseResult<>(APICode.SUCCESS.getCode(), "查询当前节点外的其他节点成功！" + TraceIDUtils.getLogTraceId(), taskList);
    }

    @ApiOperation(value = "查询消息队列", notes = "查询消息队列")
    @GetMapping(value = "/get/present/queryMq")
    @ResponseBody
    public BaseResult<List<Map.Entry<String, String>>> queryMq(@RequestParam(value = "mqKey")String mqKey) {
        if(StringUtils.isEmpty(mqKey)){
            throw new APIException(APICode.DATA_ERROR, "mqkey不能为空！");
        }
        String substring = mqKey.substring(0,mqKey.lastIndexOf("."));
        Map<String, String> map = new HashMap();
        map.put("CRM", ExchangeQueueConfig.WORK_ORDER_CRM_KEY);
        map.put("债权融资平台", ExchangeQueueConfig.WORK_ORDER_DEBT_FINANCING_KEY);
        map.put("车险分期", ExchangeQueueConfig.WORK_ORDER_INSURANCE_KEY);
        map.put("车险分期支付", ExchangeQueueConfig.WORK_ORDER_INSURANCE_PAY_KEY);
        map.put("风险预警", ExchangeQueueConfig.WORK_ORDER_WARNING_KEY);
        map.put("资产开放平台", ExchangeQueueConfig.WORK_ORDER_OPENAPI_KEY);
        map.put("统一信息视图", ExchangeQueueConfig.WORK_ORDER_VIEW_KEY);
        map.put("财资平台", ExchangeQueueConfig.WORK_ORDER_TREASURY_KEY);
        map.put("监管仓", ExchangeQueueConfig.WORK_ORDER_WAREHOUSE_KEY);
        map.put("商影", ExchangeQueueConfig.WORK_ORDER_SHANGYING_KEY);
        map.put("产品中心", ExchangeQueueConfig.WORK_ORDER_PRODUCTCENTER_KEY);
        map.put("合同管理系统", ExchangeQueueConfig.WORK_ORDER_CONTRACT_KEY);
        List<Map.Entry<String, String>> collect = new ArrayList<>(map.entrySet());
        List<Map.Entry<String, String>> mapList = collect.stream().filter(stringStringEntry -> {
            if (stringStringEntry.getValue().contains(substring)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        log.info("查询消息队列。{}", collect);
        return new BaseResult<>(APICode.SUCCESS.getCode(), "查询消息队列成功！" + TraceIDUtils.getLogTraceId(), mapList);
    }

}
